package translate_on_line;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Main {
	public static void main(String[] args) throws MalformedURLException, DocumentException {
		String word = "love";
		// dict.cn
		String word_mean = TranslateDICTCN(word);
		System.out.println(word_mean);
		// iciba
		word_mean = TranslateICIBA(word);
		System.out.println(word_mean);
	}
	
	private static String TranslateDICTCN(String word) throws MalformedURLException, DocumentException {
		String result = "";
		URL url = new URL("http://dict.cn/ws.php?utf8=true&q="+word);
		Document document = (new SAXReader()).read(url);
		Element root = document.getRootElement();
		for(Iterator<Element> i=root.elementIterator();i.hasNext();) {
			Element element = i.next();
			if(element.getName().equals("key")) {
				result = result.concat(element.getStringValue()+"\n");
			} else {
				result = result.concat("<"+element.getName()+">"+element.getStringValue()+"\n");
			}
		}
		return result;
	}
	
	private static String TranslateICIBA(String word) throws MalformedURLException, DocumentException {
		String result = "";
		URL url = new URL("http://dict-co.iciba.com/api/dictionary.php?w="+word);
		Document document = (new SAXReader()).read(url);
		Element root = document.getRootElement();
		for(Iterator<Element> i=root.elementIterator();i.hasNext();) {
			Element element = i.next();
			if(element.getName().equals("key")) {
				result = result.concat(element.getStringValue()+"\n");
			} else {
				result = result.concat("<"+element.getName()+">"+element.getStringValue()+"\n");
			}
		}
		return result;
	}
}
